library(librarian)
shelf(tidybulk, GEOquery, ggpubr, tidyverse)

preproc_bulk <- function(tdb_in, group) {
  tdb_in |>
    aggregate_duplicates() |>
    identify_abundant(factor_of_interest = {{ group }}) |>
    scale_abundance()
}

plot_qc_bulk <- function(tdb_in, scaled_abundance, group) {
  g1 <- tdb_in |>
    ggplot(aes({{ scaled_abundance }}, color= {{ group }})) +
    geom_density() +
    scale_x_log10()

  g2 <- tdb_in |>
    reduce_dimensions(method="PCA", .dims = 2) |>
    pivot_sample() |>
    ggplot(aes(PC1, PC2, color={{ group }})) +
    geom_point()
  
  print(g1 + g2)
  
  tdb_in |>
    reduce_dimensions(method="PCA", .dims = 2) |>
    pivot_sample()
}

download_ncbi_counts <- function(acc) {
  message('INFO: This function only works for human data on GEO!')
  ncbi_anno <-
  "https://www.ncbi.nlm.nih.gov/geo/download/?format=file&type=rnaseq_counts&type=rnaseq_counts&file=Human.GRCh38.p13.annot.tsv.gz" |>
    read_tsv(col_select = 1:2)
  
  "https://www.ncbi.nlm.nih.gov/geo/download/?format=file&type=rnaseq_counts&acc=GSE124676&file=GSE124676_raw_counts_GRCh38.p13_NCBI.tsv.gz" |>
    str_replace_all('GSE\\d+', acc) |>
    read_tsv() |>
    left_join(ncbi_anno) |>
    relocate(Symbol) |>
    select(-GeneID)
}

download_ncbi_meta <- function(acc, simple = TRUE) {
  ncbi_meta <- getGEO(acc) |>
    pluck(1)
  
  ncbi_meta <- ncbi_meta@phenoData@data |>
    as_tibble() |>
    select(1:2, ends_with(':ch1'))
  
  if(simple){return(ncbi_meta[,1:2])} else {return(ncbi_meta)}
}
